package com.cn.rpc;

import com.cn.msg.Message;
import com.cn.msg.ProxyMessage;
import com.cn.remote.RemoteClient;
import com.cn.util.SerializationUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.SynchronousQueue;

public class RpcProxy {

    private final static Map<String, SynchronousQueue> map = new HashMap<>();

    public static <T> T getProxy(Class<T> clz, RemoteClient client) {
        return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                ProxyMessage proxyMessage = new ProxyMessage();
                proxyMessage.setName(clz.getName());
                proxyMessage.setMethodName(method.getName());
                proxyMessage.setParamterTypes(method.getParameterTypes());
                proxyMessage.setArgs(args);
                proxyMessage.setId(String.format("%s_%d", clz.getName(), new Date().getTime()));

                Message message = new Message();
                message.setFlag((byte) 0x2);//表示消费者
                message.setType((byte) 0x5);//接口调用
                message.setByteBodys(SerializationUtil.serializeToByte(proxyMessage));
                message.setLength(message.getByteBodys().length);

                SynchronousQueue queue = new SynchronousQueue();
                map.put(proxyMessage.getId(), queue);

                client.sendMsg(message);

                return queue.take();
            }
        });
    }


    public static SynchronousQueue get(String id) {
        return map.get(id);
    }

    public static void del(String id) {
        map.remove(id);
    }

}
